<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>淘宝搜索推荐案例</title>
    <!-- 导入页面的基本样式 -->
    <link rel="stylesheet" href="./css/search.css" />
    <!-- 导入 jQuery -->
    <script src="./lib/jquery.js"></script>
    <script src="./lib/template-web.js"></script>
  </head>
  <body>
    <div class="container">
      <!-- Logo -->
      <img src="./images/taobao_logo.png" alt="" class="logo" />

      <div class="box">
        <!-- tab 栏 -->
        <div class="tabs">
          <div class="tab-active">宝贝</div>
          <div>店铺</div>
        </div>
        <!-- 搜索区域（搜索框和搜索按钮） -->
        <div class="search-box">
          <input type="text" class="ipt" placeholder="请输入要搜索的内容" /><button class="btnSearch">
            搜索
          </button>
        </div>
        <!-- 推荐框 -->
        <div id="suggest-list" style="border: 1px solid #ff5700;"></div>
      </div> 
    </div>

    <script type="text/html" id="tpl-list">
      {{each result}}
        <div>{{$value[0]}}</div>
      {{/each}}
    </script>

    <script>
      // 防抖
      $(function(){
        // 定义时间器
        var timer = null;
        // keyup防抖
        $('.ipt').on('keyup', function(){
          // 清除计时器
          clearTimeout(timer);
          // 获取处理 输入值 
          var keywords = $(this).val().trim();
          // 防抖 触发ajax请求
          timer = setTimeout(function(){
            getSuggestList(keywords)
          }, 500)
        })


      // 获取建议列表
      function getSuggestList(keywords){
          $.ajax({
            url: 'https://suggest.taobao.com/sug?q=' + keywords,
            dataType: 'jsonp',
            success: function(result){
              console.log(result);
              // 渲染到页面
              renderHtml(keywords, result)
            }
          })
      }
      
      // 渲染
      function renderHtml(keywords, result){
        if(keywords.length<= 0 || result.result.length <= 0){
          return $("#suggest-list").empty().hide();
        }
        var htmlStr = template('tpl-list', result);
        $('#suggest-list').html(htmlStr).show();
      }
      
    })
    </script>
  </body>
</html>
